package com.qf.mq;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.constant.RabbitMQConstants;
import com.qf.model.StandardReport;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.channels.Channel;

/**
 * author:z
 * time:2022/1/3 21:20
 * description:
 */
@Slf4j
@Component
public class LogMqListener {

    @Resource
    RestHighLevelClient restHighLevelClient;

    //从mq中监听到同步到es中
    @RabbitListener(queues = RabbitMQConstants.TOPIC_SMS_SEND_LOG)
    public boolean syncLog(StandardReport report, Channel channel, Message message){
        //创建es文档
        IndexRequest request = new IndexRequest();
        //文档索引名称
        request.index(RabbitMQConstants.TOPIC_SMS_SEND_LOG);
        //添加文档内容
        request.source(report);
        try {
            //es连接客户端 添加
            IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            //结果是否创建
            if (indexResponse.getResult().equals("CREATED")){
                return true;
            }
        } catch (IOException e) {
            log.error("log 同步 ES 出错");
            e.printStackTrace();
        }
        return false;
    }

}
